package com.fessc.develop.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fessc.develop.base.CCBResult;
import com.fessc.develop.entity.dbvo.TOrgConfig;
import com.fessc.develop.entity.ccbvo.CCBCallBackHeadVo;
import com.fessc.develop.entity.ccbvo.CCBResponseHeadVo;
import com.fessc.develop.model.enums.EnumResultType;
import com.fessc.develop.model.enums.EnumServiceCode;
import com.fessc.develop.handler.processor.request.CCBIBaseService;
import com.fessc.develop.service.interfaces.ITOrgConfigService;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.ExceptionUtil;
import com.fessc.develop.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CCBCallApiBaseService {

    @Resource
    List<CCBIBaseService> baseServices;

    @Resource
    private ITOrgConfigService orgConfigService;

    private Map<String, CCBIBaseService> serviceMap;

    @PostConstruct
    void init() {
        if (BusiUtil.isNotNull(baseServices)) {
            serviceMap = baseServices.stream().collect(Collectors.toMap(CCBIBaseService::getServiceCode, p -> p, (v1, v2) -> v1));
        } else {
            serviceMap = new HashMap<>();
        }
    }

    public CCBResult process(String requestBody) {
        CCBResult result;
        CCBCallBackHeadVo callBackHeadVo = new CCBCallBackHeadVo();
        try {
            // 获取报文头，进行检查、分发
            JSONObject request = JSON.parseObject(requestBody);
            log.info("ccbcallapi请求报文：" + request.toJSONString());
            //校验请求报文数据完整性
            callBackHeadVo = check(request);
            CCBIBaseService baseService = serviceMap.get(callBackHeadVo.getMsgBsnTp());
            if (BusiUtil.isNull(baseService)) {
                throw ExceptionUtil.businessException("EE4011");
            }
            result = baseService.process(requestBody);
        } catch (Exception e) {
            log.info("系统异常：" + e.getMessage());
            log.error(e.getMessage(), e);
            result = new CCBResult();
            CCBResponseHeadVo headVo = new CCBResponseHeadVo();
            headVo.setMsgbsntp(callBackHeadVo.getMsgBsnTp());
            headVo.setOrg(callBackHeadVo.getOrg());
            headVo.setCoplfid(callBackHeadVo.getCoPlfID());
            headVo.setRstdsc(BusiUtil.nvl(e.getMessage(), EnumResultType.FAIL.getMsg()));
            headVo.setRstcode(EnumResultType.FAIL.getStatusCode());
            headVo.setReqtraceid(callBackHeadVo.getReqTraceId());
            result.setHead(headVo);
            JSONObject bodyVo = new JSONObject();
            if (BusiUtil.isEquals(callBackHeadVo.getMsgBsnTp(), EnumServiceCode.CCB_HMT001.toString())) {
                bodyVo.put("ChkRes", "");
                bodyVo.put("ChkMsg", BusiUtil.nvl(e.getMessage(), EnumResultType.CCB_FAIL.getMsg()));
            } else if (BusiUtil.isEquals(callBackHeadVo.getMsgBsnTp(), EnumServiceCode.CCB_HMT002.toString())) {
                bodyVo.put("PcsgRlt", EnumResultType.CCB_FAIL.getStatusCode());
                bodyVo.put("FalRs", BusiUtil.nvl(e.getMessage(), EnumResultType.CCB_FAIL.getMsg()));
            }
            result.setBody(bodyVo);
        }
        //设置发送方流水号为请求的流水号
        result.setResponseHeaders(callBackHeadVo.getOrg(), callBackHeadVo.getCoPlfID(), callBackHeadVo.getMsgBsnTp(), callBackHeadVo.getReqTraceId(), "");
        log.info("ccbCallApi返回报文明文：" + JSON.toJSONString(result));
        return result;

    }

    public CCBCallBackHeadVo check(JSONObject request) {
        //检查检查报文是否为空
        if (BusiUtil.isNull(request)) {
            throw ExceptionUtil.businessException("EE1012");
        }
        JSONObject head = request.getJSONObject("head");
        JSONObject body = request.getJSONObject("body");
        //检查报文head是否为空
        if (BusiUtil.isNull(head)) {
            throw ExceptionUtil.businessException("EE1013");
        }
        //检查报文body是否为空
        if (BusiUtil.isNull(body) || ObjectUtil.isAllFieldNull(body)) {
            throw ExceptionUtil.businessException("EE1014");
        }
        CCBCallBackHeadVo callBackHeadVo = JSON.parseObject(head.toJSONString(), CCBCallBackHeadVo.class);
        //检查报文head字段是否为空
        if (ObjectUtil.isAllFieldNull(callBackHeadVo)) {
            throw ExceptionUtil.businessException("EE1013");
        }
        //交易结果状态回调接口（HMT005、HMT006）不判断，只判断边民备案核查与开户信息更新两个接口（HMT001、HMT002）
        if (BusiUtil.isEquals(EnumServiceCode.CCB_HMT001.toString(), callBackHeadVo.getMsgBsnTp()) ||
                BusiUtil.isEquals(EnumServiceCode.CCB_HMT002.toString(), callBackHeadVo.getMsgBsnTp())) {
            //检查服务商代码是否为空
            if (BusiUtil.isNull(callBackHeadVo.getCoPlfID())) {
                throw ExceptionUtil.businessException("EE1011");
            }
            //检查机构代码是否为空
            if (BusiUtil.isNull(callBackHeadVo.getOrg())) {
                throw ExceptionUtil.businessException("EE1001");
            }
            // 检查发起机构是否存在
            List<TOrgConfig> tOrgConfig = orgConfigService.getOrgConfigByCodePlatid("", callBackHeadVo.getOrg(), callBackHeadVo.getCoPlfID());
            if (BusiUtil.isNull(tOrgConfig)) {
                throw ExceptionUtil.businessException("EE1002");
            }
        }
        return callBackHeadVo;
    }

}
